//
//  ST_ChildStyleRegisterController.swift
//  btvideo
//
//  Created by mac on 2020/9/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import RealmSwift
import SwiftyUserDefaults
import RxSwift

class ST_ChildStyleRegisterController: UIViewController ,ST_RegisterRouteProtocol{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        view.addSubview(progress_view)
        progress_view.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 25)
            make.height.equalTo(2)
        }
        
        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.equalTo(view)
            make.height.equalTo(44)
            make.top.equalTo(progress_view.snp.bottom).offset(14)
        }
        own_navigation_bar.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        
        view.addSubview(sub_title_label)
        sub_title_label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(title_nav_btn.snp.bottom).offset(4)
        }
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(sub_title_label.snp.bottom)
            make.bottom.left.right.equalToSuperview()
        }
        
        view.addSubview(love_btn)
        
        love_btn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-25)
            make.centerX.equalToSuperview()
            make.width.equalTo(260)
            make.height.equalTo(44)
        }
        
        
        binding()
        
        
        pull_observer.onNext(())
        
        
        back_thread_execute(afterDelay: 1) {
            ST_RegisterMonitor.shared.logger.report(fromController: self)
        }
    }
    
    
    fileprivate func binding(){
        
        Observable.combineLatest(pull_observer, SCComponets.config_component.boot_config_observer).subscribe(onNext: {[weak self] _ , state in
            
            if state == .finished{
                self?.request_data()
            }
            
        }).disposed(by: disposeBag)
        
    }
    
    //    MARK: - Properties
    
    
    
    var disposeBag = DisposeBag()
    
    fileprivate let pull_observer = PublishSubject<Void>()

    func request_data(){
        
       
        JVrequest(PH.peculiarityChildListApi,parameters:["feature_id":json["id"].stringValue], success: { (json) in
            
            if let list = [ST_PeculiarityModel].deserialize(from: json["data"].rawString() ?? "") as? [ST_PeculiarityModel]{
                
                self.data_array = list.map({ (item_model) -> ST_PeculiarityModel in
                    
                    if self.selectedIds.contains(item_model.id.string){
                        item_model.isSelected = true
                    }
                    
                    return item_model
                })
            }
            
            self.collectionView.reloadData()
            
            
//            self.collectionView.selec
            
            self.update_love_btn_status()
            
        }) { (code, err) in
            
            main_thread_execute(afterDelay: 1.5) {
                self.pull_observer.onNext(())
            }
            
        }
        
        
        
    }
    
    //    MARK: - Properties
    
    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("返回_gray"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
        //        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var json:JSON = {
        
        
        let classStr = NSStringFromClass(ST_ParentStyleRegisterController.self)
        
        if let dict = ST_RegisterMonitor.shared.step_parameters[classStr]{
        
           return JSON(dict)
            
        }else{
            return JSON.null
        }
    }()
    
    fileprivate lazy var progress_view: registerProgressView = {
        let v = registerProgressView()
        v.setProgress(currentIndex: 3, amount: 4)
        return v
    }()
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium)
        
        var genderStr = "女生"
        if let sex = ST_RegisterMonitor.shared.regist_response_account()?.userinfo?.sex, sex == .female {
            genderStr = "男生"
        }
        
        let str = "选择你喜欢的" + genderStr + json["title"].stringValue + "特质"
        
        control.setTitleForAllStates(str)
        
        return control
    }()
    
    fileprivate lazy var sub_title_label: UILabel = {
        let l = UILabel()
        l.text = "特质用户都通过了AI精准人脸认证"
        l.textColor = UIColor.init(hex: 0x999999)
        l.font = .systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 30
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.sectionInset = UIEdgeInsets.init(top: 15, left: 15, bottom: BTSafeAreaBottom + 79, right: 15)
        let w = (ScreenWidth - 15*3)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_ChildStyleRegisterCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.white
        
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
//        control.allowsMultipleSelection = true
        return control
    }()
    
    fileprivate var data_array = [ST_PeculiarityModel]()
    
    fileprivate lazy var love_normal_back_image = UIImage.init(color: UIColor.init(hexString: "#DFE3E9")!, size: CGSize.init(width: 1, height: 1))
    
    fileprivate lazy var love_selected_back_image = UIImage.init(color: UIColor.init(hexString: "#FEC207")!, size: CGSize.init(width: 1, height: 1))
    
    fileprivate lazy var love_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.set_back_image_for_all_states(love_normal_back_image)
        control.setBackgroundImage(love_selected_back_image, for: UIControl.State.selected)
        control.cornerRadius = 20
        control.setTitleForAllStates("至少选择4个特质")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(love_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var register_monitor_param_key:String = {
        return  NSStringFromClass(type(of: self))
    }()
    
    fileprivate lazy var selectedIds:Set<String> = {
        
        if let ids = ST_RegisterMonitor.shared.step_parameters[register_monitor_param_key] as? Set<String>{
            return ids
        }
        return []
    }()

}

//MARK: - Event

extension ST_ChildStyleRegisterController{
    
    @objc func left_click(){
        
        self.goback_previous_controller()
        
    }
    
    @objc func love_handle(){
        
        if !love_btn.isSelected{
            return
        }
        
        self.show_indeterminate_h_u_d()
        
        selectedIds.remove("")
        
        let ids = selectedIds.joined(separator: ",")
        
        ST_RegisterMonitor.shared.step_parameters.removeValue(forKey: register_monitor_param_key)
        
        
        self.pushNextRegisterController(parameters: ["features":ids])
        
    }
    
    fileprivate func update_love_btn_status(){
        
        love_btn.isSelected = selectedIds.count >= 4
        
        if love_btn.isSelected{
            love_btn.setTitleForAllStates("选好了")
        }else{
            love_btn.setTitleForAllStates("至少选择4个特质")
        }
        
    }
    
}

extension ST_ChildStyleRegisterController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    // MARK: UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ChildStyleRegisterCell.self, for: indexPath)
        
        cell.child_model = data_array[indexPath.item]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
//        collectionView.cellForItem(at: indexPath)?.isSelected = true
        
        let id = data_array[indexPath.item].id
        
        data_array[indexPath.item].isSelected = !data_array[indexPath.item].isSelected
        
        collectionView.reloadData()
        
        if data_array[indexPath.item].isSelected{

            selectedIds.update(with: id.string)
            
        }else{
            
            selectedIds.remove(id.string)
            
        }
        
        
        
        ST_RegisterMonitor.shared.step_parameters.updateValue(selectedIds, forKey: self.register_monitor_param_key)
        
        update_love_btn_status()
    }
    
    // MARK: UICollectionViewDelegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
}




//MARK: - Cell
class ST_ChildStyleRegisterCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        
        contentView.addSubview(cover_image_view)
        contentView.addSubview(titleLabel)
        contentView.addSubview(content_label)
        
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(contentView.snp.centerY)
            make.centerX.equalTo(cover_image_view)
        }
        
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(contentView.snp.centerY)
            make.centerX.equalTo(cover_image_view)
        }
        
        contentView.addSubview(coverMask)
        coverMask.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        coverMask.addSubview(cover_selected_mask)
        cover_selected_mask.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
//        contentView.addSubview(topone_image_view)
//        topone_image_view.snp.makeConstraints { (make) in
//            make.bottom.equalTo(cover_image_view.snp.top).offset(13)
//            make.centerX.equalToSuperview()
//        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //    MARK: - Properties
    fileprivate lazy var coverMask:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.4)
        control.cornerRadius = 20
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var cover_selected_mask:UIImageView = {
        let control = UIImageView()
        control.image = ST_ImageUtils.imageName("个人中心_icon_选择sel")
        return control
    }()
    
    lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 20
        return control
    }()
    
//    lazy var topone_image_view:UIImageView = {
//        let control = UIImageView.init(image: ST_ImageUtils.imageName("topOne")!)
//        control.isHidden = true
//        return control
//    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.white
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.white
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)
        return control
    }()
    
    //    MARK:-
    var child_model = ST_PeculiarityModel(){
        didSet{
            
            coverMask.isHidden = !child_model.isSelected
            
            cover_image_view.pin_setImage(from: child_model.image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = child_model.name
            
            
            
            if let sex = ST_RegisterMonitor.shared.regist_response_account()?.userinfo?.sex,sex == .male{
                content_label.text = child_model.own_num.st_number_description() + "个女生"
            }else{
                content_label.text = child_model.own_num.st_number_description() + "个男生"
            }
            
        }
    }
    
}
